<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="WhitelistTable"
    :columns="columns"
    :row-selection="rowSelection"
    row-key="id"
  >
    <template #toolbars>
      <Row class="w-full mr-3">
        <Col :span="16">
          <Space>
            <b-button
              icon="add"
              @click="handleAdd()"
              code="monitor:whitelist:add"
              >新增</b-button
            >
            <b-button
              icon="delete"
              @click="onDelete()"
              code="monitor:whitelist:remove"
              :disabled="!selectRows.length"
              >删除</b-button
            >
          </Space>
        </Col>
        <Col :span="8" class="text-right content-center">
          <Space>
            <WithPermission code="monitor:whitelist:batch:add">
              <ImportModal
                @download-template="onDownloadTemplate"
                :upload-api="ImportWhite"
                @closed="() => tableRef.refresh()"
                accept=".xlsx, .xls"
              />
            </WithPermission>
            <b-button
              icon="export"
              @click="() => handleExport()"
              code="monitor:whitelist:export"
              :disabled="!selectRows.length"
              >导出</b-button
            ></Space
          >
        </Col>
      </Row>
    </template>
    <template #operation="{ record }">
      <b-button
        icon="edit"
        type="link"
        @click="onEdit(record)"
        code="monitor:whitelist:edit"
        >编辑</b-button
      >
      <b-button
        icon="del"
        type="link"
        @click="onDelete(record)"
        code="monitor:whitelist:remove"
        >删除</b-button
      >
    </template>
    <template #ipradius="{ record }">
      <template v-if="record.list.length === 1">
        {{ record.list[0].ipStart }} ~ {{ record.list[0].ipEnd }}
      </template>
      <template v-else>
        <Popover
          placement="right"
          trigger="click"
          :overlayStyle="{ width: '400px' }"
          overlayClassName="popovper-dark"
        >
          <template #content>
            <Table
              v-if="record.list.length > 1"
              :scroll="{ y: 300 }"
              :dataSource="record.list.slice(1) || []"
              :pagination="false"
            >
              <TableColumn dataIndex="ipStart" title="起始IP" align="center" />
              <TableColumn dataIndex="ipEnd" title="结束IP" align="center" />
            </Table>
          </template>
          <span style="cursor: pointer"
            >{{ record.list[0].ipStart }} ~
            {{ record.list[0].ipEnd }}
            <RightOutlined />
          </span>
        </Popover>
      </template>
    </template>
    <template #time="{ record }">
      {{ record.effectStartTime }} -
      {{ record.effectEndTime || '2050-01-01 00:00:00' }}
    </template>
  </ProTable>

  <FormModal :items="items">
    <template #list="{ formState }">
      <inputIp :list="formState.list" />
    </template>
    <template #after-content>
      <ul class="remark-content">
        <li>
          添加到白名单中的IP地址可以访问<span style="color: #40deff"
            >{ 预警终端管理系统 }</span
          >
        </li>
        <li>· 可以填写IP地址（如192.168.0.1）或IP段（如192.168.0.0/24）</li>
        <li>- 举例：指定ip地址 起始ip 111.132.134.1 结束ip 111.132.134.1</li>
        <li>- 举例：指定ip段 起始ip 111.132.134.1 结束ip 111.132.134.255</li>
        <li>· 白名单IP地址设置为127.0.0.1，表示该IP地址可以访问。</li>
      </ul>
    </template>
  </FormModal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { WithPermission, hasPermission } from '@/permission';
import { RightOutlined } from '@ant-design/icons-vue';
import {
  Col,
  Modal,
  Popover,
  Row,
  Space,
  Table,
  TableColumn,
  message,
} from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { download } from '@/utils/utils';
import {
  AddWhite,
  EditWhiteIp,
  ExportWhite,
  ImportWhite,
  WhitelistTable,
  delWhiteIplist,
  downloadTemplate,
} from '@/api/monitor';
import ImportModal from '../components/ImportModal.vue';
import inputIp from '../components/inputIp.vue';

const tableRef = ref();
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: 'IP分组名称',
    dataIndex: 'ipGroup',
    fixed: 'left',
    width: 150,
  },
  {
    title: 'IP地址',
    dataIndex: 'ipStart',
    hideInTable: true,
  },
  {
    title: 'IP范围',
    dataIndex: 'ipradius',
    hideInSearch: true,
    width: 250,
  },
  {
    title: '数量',
    dataIndex: 'ipNumber',
    hideInSearch: true,
  },
  {
    title: '生效时间',
    dataIndex: 'time',
    hideInSearch: true,
    width: 300,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 150,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: 'IP分组名称',
    type: 'input',
    field: 'ipGroup',
    rules: [
      {
        required: true,
        message: '请输入ip分组名称',
        trigger: 'blur',
      },
      {
        min: 2,
        max: 120,
        message: 'ip分組名称长度必须介于 2 和 120 之间',
        trigger: 'blur',
      },
    ],
  },
  {
    label: 'IP地址',
    type: 'input',
    field: 'list',
    rules: [
      {
        required: true,
        type: 'array',
        message: '请添加IP起始地址',
        trigger: 'blur',
      },
    ],
  },
  {
    label: '生效时间',
    type: 'dateRange',
    field: 'dateRange',
    rules: [
      {
        required: true,
        type: 'array',
        message: '请输入生效时间',
        trigger: 'blur',
      },
    ],
    props: {
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      showTime: true,
    },
  },
]);
const { FormModal, open } = useFormModal({
  size: 'small',
  column: 1,
  formProps: { labelCol: { span: 4 } },
});
const selectRows = ref<any[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    onChange(values, selectedRows) {
      selectRows.value = selectedRows;
    },
  };
});

const handleExport = () => {
  const ids = selectRows.value.map((item) => item.id).join();
  ExportWhite(ids).then((res) => {
    download(
      res as unknown as Blob,
      `${new Date().getTime()}_export_white.xlsx`,
    );
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async (row?: any) => {
  const ids = row?.id || selectRows.value.map((item) => item.id).join();
  const ipGroups =
    row?.ipGroup || selectRows.value.map((item) => item.ipGroup).join();
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `是否确认删除ip分组为"${ipGroups}"的数据项？`,
    onOk: async () => {
      await delWhiteIplist(ids);
      sleep(() => tableRef.value.refresh());
      message.success('操作成功');
    },
  });
};
const onEdit = (row: any) => {
  open({
    title: '编辑',
    defaultValue: {
      ...row,
      dateRange: [row.effectStartTime, row.effectEndTime],
    },
    serviceApi: async (params: any): Promise<any> => {
      let effectStartTime = params.dateRange[0];
      let effectEndTime = params.dateRange[1];
      let ipNumber = 0;
      params.list.forEach((item: any) => {
        const ipStart = item.ipStart.split('.');
        const ipEnd = item.ipEnd.split('.');
        ipNumber += parseInt(ipEnd[3]) - parseInt(ipStart[3]) + 1;
      });
      await EditWhiteIp({
        ...params,
        ipNumber,
        effectStartTime,
        effectEndTime,
      });
      tableRef.value.refresh();
    },
  });
};
const handleAdd = () => {
  open({
    title: '新增',
    defaultValue: {
      list: [],
    },
    serviceApi: async (params: any): Promise<any> => {
      let effectStartTime = params.dateRange[0];
      let effectEndTime = params.dateRange[1];
      let ipNumber = 0;
      params.list.forEach((item: any) => {
        const ipStart = item.ipStart.split('.');
        const ipEnd = item.ipEnd.split('.');
        ipNumber += parseInt(ipEnd[3]) - parseInt(ipStart[3]) + 1;
      });
      await AddWhite({ ...params, ipNumber, effectStartTime, effectEndTime });
      tableRef.value.refresh();
    },
  });
};
const onDownloadTemplate = async () => {
  const res = await downloadTemplate();
  download(res as unknown as Blob, '白名单导入模板.xlsx');
};
</script>
<style lang="scss" scoped>
.remark-content {
  font-size: 14px;
  padding: 20px 30px;
  line-height: 25px;
  border-radius: 2px;
  border: 1px dashed #ccc;
}
</style>
